package com.market.fleamarket.controller;

import com.market.fleamarket.entity.User;
import com.market.fleamarket.repository.UserRepository;
import com.market.fleamarket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/admin")
public class AdminController {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    // 验证当前用户是否为管理员
    private void validateAdmin(HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            throw new RuntimeException("没有权限执行此操作");
        }
    }

    @GetMapping("/users")
    public List<User> getAllUsers(HttpSession session) {
        validateAdmin(session);
        return userRepository.findAll();
    }

    @PutMapping("/users/{id}/role")
    public User updateUserRole(@PathVariable Long id, @RequestParam String role, HttpSession session) {
        validateAdmin(session);
        User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setRole(role);
        return userRepository.save(user);
    }

    @PostMapping("/users/{id}/approve")
    public User approveUser(@PathVariable Long id, HttpSession session) {
        validateAdmin(session);
        return userService.approveUser(id);
    }

    @PostMapping("/users/{id}/reject")
    public User rejectUser(@PathVariable Long id, HttpSession session) {
        validateAdmin(session);
        return userService.rejectUser(id);
    }

    @DeleteMapping("/users/{id}")
    public Object deleteUser(@PathVariable Long id, HttpSession session) {
        try {
            validateAdmin(session);

            // 检查是否尝试删除自己
            User currentUser = (User) session.getAttribute("user");
            if (currentUser.getId().equals(id)) {
                return java.util.Collections.singletonMap("error", "不能删除当前登录的用户");
            }

            userRepository.deleteById(id);
            return java.util.Collections.singletonMap("success", true);
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }
} 